package ws.jonas.sybosc.gui;

import java.util.ArrayList;
import java.util.List;

import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

@SuppressWarnings("serial")
public abstract class SearchOption<T> extends JPanel {
	protected final JLabel description;

	public SearchOption(String description) {
		setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
		this.description = new JLabel(description);
		add(this.description);
	}

	public abstract void refresh();

	public T getSingleSelection() {
		return null;
	}

	public List<T> getMultipleSelections() {
		return null;
	}

	public static class MultiSelectionListOption<T> extends SearchOption<T> {
		private final JList list;
		private final MultiSelectionListWorker<T> worker;

		public MultiSelectionListOption(String description, MultiSelectionListWorker<T> worker) {
			super(description);
			this.worker = worker;
			list = new JList();
			add(new JScrollPane(list));
		}

		public void refresh() {
			if (worker != null) {
				T[] values = worker.getNewValues();
				if (values != null) {
					list.setListData(values);
				}
			}
		}

		@SuppressWarnings("unchecked")
		@Override
		public List<T> getMultipleSelections() {
			List<T> selections = new ArrayList<T>();
			for (Object o : list.getSelectedValues()) {
				selections.add((T)o);
			}
			return selections;
		}

		public static interface MultiSelectionListWorker<T> {
			public T[] getNewValues();
		}
	}

	/*  --- REQUIRES JDK 1.7 ---
	public static class MultiSelectionListOption<T> extends SearchOption<T> {
		private final JList<T> list;
		private final MultiSelectionListWorker<T> worker;

		public MultiSelectionListOption(String description, MultiSelectionListWorker<T> worker) {
			super(description);
			this.worker = worker;
			list = new JList<T>();
			add(new JScrollPane(list));
		}

		public void update() {
			if (worker != null) {
				list.setListData(worker.getNewValues());
			}
		}

		@Override
		public List<T> getMultipleSelections() {
			List<T> selections = new ArrayList<T>();
			for (T o : list.getSelectedValuesList()) {
				selections.add(o);
			}
			return selections;
		}

		public static interface MultiSelectionListWorker<T> {
			public T[] getNewValues();
		}
	}
	*/

	public static class DateOption extends SearchOption<String> {
		private final JTextField field;
		private final DateOptionWorker worker;

		public DateOption(String description, DateOptionWorker worker) {
			super(description);
			this.worker = worker;
			field = new JTextField();
			add(field);
		}

		@Override
		public void refresh() {
			if (worker != null) {
				field.setText(worker.getNewValue());
			}
		}

		@Override
		public String getSingleSelection() {
			return field.getText();
		}

		public static interface DateOptionWorker {
			public String getNewValue();
		}
	}
}
